<?php
// JANUS config includes
require_once $_SERVER['DOCUMENT_ROOT'] . '/../include/apps/janus/config/config.php';

/**
 * Various utility functions for JANUS Facebook application
 */
class JanusUtilityFuncs {

	/**
	 * Returns the content at a remote location as a string
	 * @param string $uri
	 */
	public static function getRemoteContent($uri)
	{
		$curlHandle = curl_init();
		$timeout    = 0; // Set to zero for no timeout

		$options = array(
			CURLOPT_URL => $uri,
			CURLOPT_USERAGENT => "JANUS Facebook application",
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_CONNECTTIMEOUT => $timeout
		);
		
		curl_setopt_array($curlHandle, $options);
		
		$content = curl_exec($curlHandle);
		curl_close($curlHandle);

		return $content;
	}

	/**
	 * 
	 * @param SimpleXMLElement $entry
	 */
	public static function getEntityIdFromEntry(SimpleXMLElement $entry)
	{
		$id = null;
		
		$fullId = $entry->id;
		$lastSlashPos = strrchr($fullId, '/');
		
		if ($lastSlashPos === false)
		{
			$id = $fullId;
		}
		else
		{
			$id = substr($lastSlashPos, 1);
		}
		
		return $id;
	}
	
	/**
	 * Returns the XML resulting from a request to the JANGLE core
	 * @param string $request The URI to send to the JANGLE core
	 */
	public static function getJangleXml($request)
	{
		libxml_use_internal_errors(true);
		libxml_clear_errors();
		
		$remoteContent = JanusUtilityFuncs::getRemoteContent($request);
		$xml = simplexml_load_string($remoteContent);
		return $xml;
	}
	
	/**
	 * Returns the actor XML feed for the specified id from the JANGLE core 
	 * @param string $id The id of the actor
	 */
	public static function getActorXmlById($id)
	{
		$jangleUri = $GLOBALS['JANGLE']['BASE_URI'] . $GLOBALS['JANGLE']['CONNECTOR'] . '/actors/' . $id;
		$xml = JanusUtilityFuncs::getJangleXml($jangleUri);
		return $xml;
	}
	
	/**
	 * Returns a URI for a related entities feed in a feed entry 
	 * @param SimpleXmlElement $entryXml The XML of an entry from a feed from the JANGLE core
	 * @param string $jangleRelationship The JANGLE vocabulary relationship string that indicates which related link to retrieve
	 */
	public static function getRelatedEntitiesUri(SimpleXMLElement $entryXml, $jangleRelationship)
	{
		$links = $entryXml->link;
		
		if (count($links) > 0)
		{
			foreach ($links as $link)
			{
				$attributes = $link->attributes();
				$jangleAttributes = $link->attributes($GLOBALS['NAMESPACE']['JANGLE_VOCABULARY']);
				
				if ($jangleAttributes['relationship'] == $jangleRelationship
				    && $attributes['rel'] == 'related')
				{
					return $attributes['href'];
				}
			}
		}
		
		return false;
	}
	
	/**
	 * Returns the URI of the related ACTOR feed in a feed entry 
	 * @param SimpleXmlElement $entryXml The XML of an entry from a feed from the JANGLE core
	 */
	public static function getRelatedActorsUri(SimpleXMLElement $entryXml)
	{
		return JanusUtilityFuncs::getRelatedEntitiesUri($entryXml, $GLOBALS['JANGLE']['RELATIONSHIP']['ACTOR']);
	}
	
	/**
	 * Returns the URI of the related ITEM feed in a feed entry 
	 * @param SimpleXmlElement $entryXml The XML of an entry from a feed from the JANGLE core
	 */
	public static function getRelatedItemsUri(SimpleXMLElement $entryXml)
	{
		return JanusUtilityFuncs::getRelatedEntitiesUri($entryXml, $GLOBALS['JANGLE']['RELATIONSHIP']['ITEM']);
	}
	
	/**
	 * Returns the URI of the related RESOURCE feed in a feed entry 
	 * @param SimpleXmlElement $entryXml The XML of an entry from a feed from the JANGLE core
	 */
	public static function getRelatedResourcesUri(SimpleXMLElement $entryXml)
	{
		return JanusUtilityFuncs::getRelatedEntitiesUri($entryXml, $GLOBALS['JANGLE']['RELATIONSHIP']['RESOURCE']);
	}
	
	/**
	 * Returns the display markup generated from an ITEM feed entry
	 * @param SimpleXMLElement $itemEntry
	 */
	public static function getItemInfoMarkup(SimpleXMLElement $itemEntry)
	{
		$output = '';
		
		// Getting the due date for the item. Remember, an ITEM is a specific copy of a RESOURCE (or book in this case)
		// so an ACTOR (user) can have ITEMS on loan, which are literally copies of RESUORCES (books)
		$itemDlfRecord = $itemEntry->content->children($GLOBALS['NAMESPACE']['DLF'])->record;
		$itemDue = $itemDlfRecord->items->item->simpleavailability->dateavailable;
		
		// Want the resource XML to look up the bibliographic data for the RESOURCE 
		$resourceXml = JanusUtilityFuncs::getJangleXml(JanusUtilityFuncs::getRelatedResourcesUri($itemEntry));
		
		if ($resourceXml !== false)
		{
			$resourceEntry = $resourceXml->children()->entry[0];
			
			$resourceTitle = $resourceEntry->title;
			$resourceAuthor = $resourceEntry->author->name;
			
			$output .= "<hr />\n";
	
			// Example of using a template file and replacements.
			// Create MarkupTemplate object
			$template = new MarkupTemplate();
			
			// Load a template from a file. 2nd param means it will automatically detect codes and add them to the internal list
			$template->loadTemplateFile($GLOBALS['TEMPLATES']['BASE_PATH'] . 'book_info_table.tpl', true);
			
			// Replacement codes already loaded, so UPDATE them rather than ADD
			// Note: typecast to (string) because that's what the update func is looking for
			$template->updateReplacement('BOOK_TITLE', (string)$resourceTitle, false);
			$template->updateReplacement('BOOK_AUTHOR', (string)$resourceAuthor, false);
			$template->updateReplacement('BOOK_DUE_BACK', (string)$itemDue, false);
			
			// Output the markup with replacements applied
			$output .= $template->getOutputMarkup();
		}
		else
		{
			$isError = true;
			$output .= "<p>Failed to load resource XML</p>\n";
		}
		
		return $output;
	}
	
	/**
	 * Returns the display markup for the current loans for the specified actor
	 * @param string $actorId The id of the actor
	 */
	public static function getCurrentLoansMarkup($actorId)
	{
		$output = '';
		
		$actorXml = JanusUtilityFuncs::getActorXmlById($actorId);
		
		if ($actorXml !== false)
		{
			$actorEntry = $actorXml->children()->entry[0];
			
			// Create a new VCard object to store the ACTOR (user) data
			$actorVCard = new VCard();
			$actorVCard->loadFromString($actorEntry->content[0]);
			$actorName = htmlspecialchars($actorVCard->getFieldValue('FN'));
			
			$output .= "<h2>Current loans for $actorName</h2>\n";
			
			$itemsXml = JanusUtilityFuncs::getJangleXml(JanusUtilityFuncs::getRelatedItemsUri($actorEntry));
			
			if ($itemsXml !== false)
			{
				$itemEntries = $itemsXml->children()->entry;
				
				if (count($itemEntries) > 0)
				{
					foreach ($itemEntries as $itemEntry)
					{
						$output .= JanusUtilityFuncs::getItemInfoMarkup($itemEntry);
					}
				}
				else
				{
					$output .= "<p>No items were found</p>\n";
				}
			}
			else
			{
				$isError = true;
				$output .= "<p>Failed to load items XML</p>\n";
			}
		}
		else
		{
			$isError = true;
			$output .= "<p>Failed to load actor XML</p>\n";
		}
		
		return $output;
	}
	
}
